/*
 * circbuffer.c
 *
 *  Created on: 2015-03-19
 *      Author: atreyu
 */

#include "circbuffer.h"

int init_cBuffer(cBuffer *cB, size_t capacity, size_t sz)
{
	cB->buffer = malloc(capacity * sz);
	if(cB->buffer == NULL)
	{
		//error
		bt_UARTsend("Buffer error!\r\n");
		return 0;
	}
	cB->buffer_end = (char *)cB->buffer + capacity * sz;
	cB->capacity = capacity;
	cB->count = 0;
	cB->sz = sz;
	cB->head = cB->buffer;
	cB->tail = cB->buffer;
	return 1;
}

void cBuffer_free(cBuffer *cB)
{
	free(cB->buffer);
	bt_UARTsend("ADC Buffer...Free\r\n");
	//clear out everything
	return;
}

int cBuffer_push_end(cBuffer *cB, const void *item)
{
	if(cB->count == cB->capacity)
	{
		//error
		bt_UARTsend("Push...Fail\r");
		cBuffer_pop_top(cB, &item);
		return 0;
	}
	else
	{
		//bt_UARTsend("Push...OK");
		memcpy(cB->head, item, cB->sz);
		cB->head = (char*)cB->head + cB->sz;
		if(cB->head == cB->buffer_end)
			cB->head = cB->buffer;
		cB->count++;
		return 1;
	}
}

int cBuffer_pop_top(cBuffer *cB, void *item)
{
	//bt_UARTsend("Pop...OK\r\n");
	if(cB->count == 0)
	{
		//error
		bt_UARTsend("Pop...Fail\r\n");
		return 0;
	}
	else
	{
		//bt_UARTsend("Pop...OK\r");
		memcpy(item, cB->tail, cB->sz);
		cB->tail = (char*)cB->tail + cB->sz;
		if(cB->tail == cB->buffer_end)
			cB->tail = cB->buffer;
		cB->count--;
		return 1;
	return 1;
	}
}

int cBuffer_normalize(cBuffer *cB)
{
	//bt_UARTsend("Normalizing buffer...OK\r\n");

	return 0;
}

void cBuffer_print(cBuffer *cB)
{
	cBuffer* currentNode = cB->buffer;
	while(currentNode != NULL)
	{
		bt_UARTsend(currentNode->buffer);
		currentNode=currentNode->tail;
	}
	//bt_UARTputc(48+);
}

